package net.qhzw.vip.qiyu.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import ma.glasnost.orika.MapperFacade;
import net.qhzw.vip.qiyu.dto.ProductDto;
import net.qhzw.vip.qiyu.entity.Product;
import net.qhzw.vip.qiyu.entity.Sku;
import net.qhzw.vip.qiyu.entity.Transport;
import net.qhzw.vip.qiyu.result.JsonResult;
import net.qhzw.vip.qiyu.service.MallUserVipService;
import net.qhzw.vip.qiyu.service.ProductService;
import net.qhzw.vip.qiyu.service.SkuService;
import net.qhzw.vip.qiyu.service.TransportService;
import net.qhzw.vip.qiyu.util.Arith;
import net.qhzw.vip.qiyu.util.Json;
import net.qhzw.vip.qiyu.util.PageParam;
import net.qhzw.vip.qiyu.util.SecurityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/prod")
@Api(tags = "商品接口")
public class ProdController {

    @Autowired
    private ProductService prodService;

    @Autowired
    private SkuService skuService;

    @Autowired
    private MapperFacade mapperFacade;

    @Autowired
    private TransportService transportService;

    @Autowired
    private MallUserVipService userVipService;

    @GetMapping("/pageProd")
    @ApiOperation(value = "通过分类id商品列表信息", notes = "根据分类ID获取该分类下所有的商品列表信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "categoryId", value = "分类ID", required = true, dataType = "Long"),
    })
    public JsonResult<IPage<ProductDto>> prodList(
            @RequestParam(value = "categoryId") Long categoryId, PageParam<ProductDto> page) {
        IPage<ProductDto> productDtoIPage = prodService.pageByCategoryId(page, categoryId);
        List<ProductDto> records = productDtoIPage.getRecords();
        if (!CollectionUtils.isEmpty(records)) {
            for (ProductDto record : records) {
                double platform = Arith.add(record.getSiteFee(), record.getPlatformFee());
                record.setPrice(Arith.add(record.getPrice(), platform));
                record.setOriPrice(Arith.add(record.getOriPrice(), platform));
                record.setVipPrice(Arith.add(record.getVipPrice(), platform));
            }
        }

        return JsonResult.ok(productDtoIPage);
    }

    @GetMapping("/prodInfo")
    @ApiOperation(value = "商品详情信息", notes = "根据商品ID（prodId）获取商品信息")
    @ApiImplicitParam(name = "prodId", value = "商品ID", required = true, dataType = "Long")
    public JsonResult<ProductDto> prodInfo(Long prodId) {
        Product product = prodService.getProductDtoByProdId(prodId);
        if (product == null) {
            return JsonResult.ok(null);
        }
        //平台使用费 + 站点费用 +站点运费 SPU
        double prodPlatform = Arith.add(product.getPlatformFee(), product.getSiteFee());
        product.setOriPrice(Arith.add(product.getOriPrice(), prodPlatform));
        product.setPrice(Arith.add(product.getPrice(), prodPlatform));

//        product.setVipPrice(Arith.add(product.getVipPrice(), Arith.add(product.getVipPlatformFee(), product.getSiteFee())));
        product.setVipPrice(Arith.add(product.getVipPrice(), product.getVipPlatformFee()));
        List<Sku> skuList = skuService.listByProdId(prodId);
        // 启用的sku列表
        List<Sku> useSkuList = skuList.stream().filter(sku -> sku.getStatus() == 3).collect(Collectors.toList());
        product.setSkuList(rePlatformfees(useSkuList));
        ProductDto productDto = mapperFacade.map(product, ProductDto.class);
        Long userId = SecurityUtils.getUserId();
        //查询该用户是否VIP
        Integer mallVip = userVipService.selectUserVip(userId, product.getShopId());
        productDto.setMallVip(mallVip);
        // 商品的配送方式
        Product.DeliveryModeVO deliveryModeVO = Json.parseObject(product.getDeliveryMode(), Product.DeliveryModeVO.class);
        // 有店铺配送的方式, 且存在运费模板，才返回运费模板的信息，供前端查阅
        if (deliveryModeVO.getHasShopDelivery() && product.getDeliveryTemplateId() != null) {
            Transport transportAndAllItems = transportService.getTransportAndAllItems(product.getDeliveryTemplateId());
            productDto.setTransport(transportAndAllItems);
        }
        return JsonResult.ok(productDto);
    }


    /**
     * 添加平台费用
     *
     * @param useSkuList
     * @return
     */
    private List<Sku> rePlatformfees(List<Sku> useSkuList) {
        if (!CollectionUtils.isEmpty(useSkuList)) {
            //平台使用费 + 站点费用 +站点运费 sku
            for (Sku sku : useSkuList) {
                double sukPlatform = Arith.add(sku.getPlatformFee(), sku.getSiteFee());
                sku.setOriPrice(Arith.add(sukPlatform, sku.getOriPrice()));
                sku.setPrice(Arith.add(sukPlatform, sku.getPrice()));
                //sku.setVipPrice(Arith.add(Arith.add(sku.getVipPlatformFee(), sku.getSiteFee()), sku.getVipPrice()));
                sku.setVipPrice(Arith.add(sku.getVipPrice(), sku.getVipPlatformFee()));
            }
        }

        return useSkuList;
    }

    @GetMapping("/prodListByTagId")
    @ApiOperation(value = "通过分组标签获取商品列表", notes = "通过分组标签id（tagId）获取商品列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "tagId", value = "当前页，默认为1", required = true, dataType = "Long"),
    })
    public JsonResult<IPage<ProductDto>> prodListByTagId(@RequestParam(value = "tagId") Long tagId, PageParam<ProductDto> page) {
        IPage<ProductDto> productDtoIPage = prodService.pageByTagId(page, tagId);
        return JsonResult.ok(productDtoIPage);
    }

}
